/**
 * This file contains functions for filtering.
 */

/**
 * Add a row to the given table containing the given parameters.
 */
function addRow(tableId, type, key, expression) {
	var table = document.getElementById(tableId);
	var rowCount = table.rows.length;
	var row = table.insertRow(rowCount);

	var cell1 = row.insertCell(0);
	cell1.innerHTML = rowCount;

	var cell2 = row.insertCell(1);
	cell2.innerHTML = type;

	var cell3 = row.insertCell(2);
	cell3.innerHTML = key;

	var cell4 = row.insertCell(3);
	cell4.innerHTML = expression;

	var cell5 = row.insertCell(4);
	var delButton = document.createElement("input");
	delButton.setAttribute("type", "button");
	delButton.setAttribute("onClick", "deleteRow('filter', '" + rowCount + "')");
	delButton.setAttribute("value", "Delete");
	cell5.appendChild(delButton);
}

/**
 * Delete the specified row from the specified table
 */
function deleteRow(tableId, rowId) {
	var table = document.getElementById(tableId);
	var rowCount = table.rows.length;

	for(var i = 1; i < rowCount; i++) {
		var row = table.rows[i];
		var rowNum = row.cells[0].innerHTML;
		if(rowNum == (rowId + "")) {
			//remove the row
			table.deleteRow(i);
			rowCount--;
			i--;
		} else if(rowNum > (i + "")) {
			//update rows numbers
			row.cells[0].innerHTML = i;
			row.cells[4].childNodes[0].setAttribute("onClick", "deleteRow('filter', '" + i + "')")
		}
	}
}

/**
 * Delete all the rows from the specified table
 */
function clearTable(tableId) {
	var table = document.getElementById(tableId);
	var rowCount = table.rows.length;

	for(var i = 1; i < rowCount; i++) {
		var row = table.rows[i];
		var rowNum = row.cells[0].innerHTML;
		//remove the row
		table.deleteRow(i);
		rowCount--;
		i--;
	}
}

/**
 * Apply the filters stored in the given table
 */
function applyFilters(tableId) {
	// get table
	var table = document.getElementById(tableId);
	var rowCount = table.rows.length;
	var filters = []
	// create filters' list
	for(var i = 1; i < rowCount; i++) {
		var row = table.rows[i];
		var filter = {}
		filter["type"] = row.cells[1].innerHTML;
		filter["key"] = row.cells[2].innerHTML;
		filter["regexp"] = row.cells[3].innerHTML;
		filters[filters.length] = filter;
	}
	//alert(JSON.stringify(filters))
	// server request
	method = "post"; 
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", "filterData");   
    var params = {'couchdb':couchdb, 'database':project, 'filterList':JSON.stringify(filters), 'dateType':datatime}
    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }
    document.body.appendChild(form);
    form.submit();
}
